//
//  ST_UnlockNearbyController.swift
//  btvideo
//
//  Created by mac on 2019/12/11.
//  Copyright © 2019 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON
import SwiftyAttributes
import MBProgressHUD

class ST_UnlockNearbyController: UIViewController,ST_TIANPaymentTransactionStateDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = Color.clear
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.width.equalTo(320)
            make.height.equalTo(450)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        root_view.addSubview(title_btn)
        title_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(33)
            make.width.equalTo(170)
            make.height.equalTo(30)
        }
        
        root_view.addSubview(center_image_view)
        center_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(title_btn.snp.bottom).offset(14)
            make.width.equalTo(90)
            make.height.equalTo(80)
        }
        
        root_view.addSubview(center_label)
        center_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(center_image_view.snp.bottom).offset(14)
        }
        
        
        root_view.addSubview(pay_item_view1)
        root_view.addSubview(pay_item_view2)
        root_view.addSubview(pay_item_view3)
        
        pay_item_view1.click_closure = {[weak self] in
            guard let strongSelf = self else {
                return
            }
            strongSelf.last_selected_item.modify_status(select: false)
            strongSelf.last_selected_item = strongSelf.pay_item_view1
        }
        
        pay_item_view2.click_closure = {[weak self] in
            guard let strongSelf = self else {
                return
            }
            strongSelf.last_selected_item.modify_status(select: false)
            strongSelf.last_selected_item = strongSelf.pay_item_view2
        }
        
        pay_item_view3.click_closure = {[weak self] in
            guard let strongSelf = self else {
                return
            }
            strongSelf.last_selected_item.modify_status(select: false)
            strongSelf.last_selected_item = strongSelf.pay_item_view3
        }
        
        
        pay_item_view2.snp.makeConstraints { (make) in
            make.width.equalTo(90)
            make.height.equalTo(110)
            make.centerX.equalToSuperview()
            make.top.equalTo(center_label.snp.bottom).offset(30)
        }
        
        
        pay_item_view1.snp.makeConstraints { (make) in
            make.width.height.equalTo(pay_item_view2)
            make.right.equalTo(pay_item_view2.snp.left).offset(-10)
            make.top.equalTo(pay_item_view2)
        }
        
        pay_item_view3.snp.makeConstraints { (make) in
            make.width.height.equalTo(pay_item_view2)
            make.left.equalTo(pay_item_view2.snp.right).offset(10)
            make.top.equalTo(pay_item_view2)
        }
        
        root_view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(36)
            make.centerX.equalToSuperview()
            make.top.equalTo(pay_item_view2.snp.bottom).offset(30)
        }
        
        root_view.addSubview(cancel_btn)
        cancel_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.top.equalTo(confirm_btn.snp.bottom).offset(7)
        }
        
        
        self.view.addSubview(purchase_cancel_sub_label)
        purchase_cancel_sub_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(root_view.snp.bottom).offset(24)
        }
        
        self.view.addSubview(purchase_cancel_content_label)
        purchase_cancel_content_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(purchase_cancel_sub_label.snp.bottom)
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
        }
        
        
        request_data()
        
    }
    
    
    func request_data(){
        
        JVrequest(PH.showApplePriceApi, success: { (json) in
            
            if let list = [ST_JVPayItemViewModel].deserialize(from: json["data"]["same_city"].rawString()) as? [ST_JVPayItemViewModel]{
                
                if let item = list[safe:0]{
                    self.pay_item_view1.model = item
                }
                
                if let item = list[safe:1]{
                    self.pay_item_view2.model = item
                }
                
                if let item = list[safe:2]{
                    self.pay_item_view3.model = item
                }
            }
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
    }
    
    fileprivate var first_selected = false
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        if !pay_item_view2.selected_btn.isSelected && first_selected == false {
            
            pay_item_view2.modify_status(select: true)
            pay_item_view1.modify_status(select: false)
            pay_item_view3.modify_status(select: false)
            
            first_selected = true
        }
    }
    

    
//    MARK: - Properties
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.cornerRadius = 20
        control.backgroundColor = Color.white
        return control
    }()
    
    fileprivate lazy var male_describe = "解锁同城功能"
    
    fileprivate lazy var female_describe = "解锁同城精选"

    fileprivate lazy var title_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        if let sex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex,sex != .female{
            control.setTitleForAllStates(male_describe)
        }else{
            let image = ST_ImageUtils.imageName("首页_icon_同城精选")!
            control.setImageForAllStates(image)
            control.setTitleForAllStates(female_describe)
        }
        
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        
        control.semanticContentAttribute = .forceRightToLeft
        
        control.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        
        return control
    }()
    
    fileprivate lazy var center_image_view:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("首页_img_解锁同城")
        return control
    }()

    fileprivate lazy var center_label:UILabel = {
        let label = UILabel()
        var str = "无限查看同城最佳精选男生"
        if let sex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex,sex != .female{
            str = "对同城女生超级喜欢，回复率提升500%"
        }
        let attrString = NSMutableAttributedString(string: str)
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    fileprivate lazy var last_selected_item:ST_JVPayItemView = {
       return pay_item_view2
    }()
    
    fileprivate lazy var pay_item_view1:ST_JVPayItemView = {
        let control = ST_JVPayItemView()
        return control
    }()
    
    fileprivate lazy var pay_item_view2:ST_JVPayItemView = {
        let control = ST_JVPayItemView()
        return control
    }()
    
    fileprivate lazy var pay_item_view3:ST_JVPayItemView = {
        let control = ST_JVPayItemView()
        return control
    }()
    
    
    fileprivate lazy var confirm_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("继续")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.white)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 18
        control.add_touch_up(insideTarget: self, action: #selector(confirm_handle))
        return control
    }()
    
    fileprivate lazy var cancel_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("不用了，谢谢")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#999999")!)
        control.add_touch_up(insideTarget: self, action: #selector(cancel_handle))
        return control
    }()
    
    
    fileprivate lazy var purchase_cancel_sub_label:UILabel = {
        let control = UILabel.init()
        control.text = "自动订阅，随时取消"
        control.textColor = Color.init(hexString: "#999999")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var purchase_cancel_content_label:UITextView = {
        
        let control = UITextView.init()
        
        control.delegate = self
        control.isEditable = false
        control.isScrollEnabled = false
        
        control.backgroundColor = Color.clear
        
        control.tintColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        
        control.textAlignment = .center
        
        
        
        let attrString = NSMutableAttributedString(string: "购买订阅的费用将从你的iTunes账户收取，到期前24小时会自动扣费并续订服务，购买后可随时前往iTunes商店的设置页面取消订阅。点击购买即表示同意")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.regular),.foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        attrString.append(privacy_link_attribute)
        
        
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = .center
        paragraph.lineSpacing = 3
        
        let centerAttr : [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle:paragraph]
        attrString.addAttributes(centerAttr, range: NSRange(location: 0, length: attrString.length))
        
        control.attributedText = attrString
        
        return control
    }()
    
    
    lazy var privacy_link_attribute:NSAttributedString = {
        
        let attr = "《服务条款》".withAttributes([Attribute.font(Font.systemFont(ofSize: 10)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!),Attribute.link(URL.init(string: PH.serviceProtocolURL)!)])
        
        let attr1 = "及".withAttributes([Attribute.font(Font.systemFont(ofSize: 10)),Attribute.textColor(UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))])
        
        let attr2 = "《隐私政策》".withAttributes([Attribute.font(Font.systemFont(ofSize: 10)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!),Attribute.link(URL.init(string: PH.privacyProtocolURL)!)])
        
        attr.append(attr1)
        
        attr.append(attr2)
        
        return attr
    }()
    
    
//    MARK: - success Toast properties
    fileprivate lazy var success_root_view:UIView = {
       let control = UIView()
        control.cornerRadius = 20
        control.backgroundColor = Color.white
        return control
    }()
    
    fileprivate lazy var success_title_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        
        control.setTitleForAllStates("支付成功")
        
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        
        control.semanticContentAttribute = .forceRightToLeft
        
        control.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        
        return control
    }()
    
    fileprivate lazy var success_center_image_view:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("首页_img_支付成功")
        return control
    }()

    fileprivate lazy var success_center_label:UILabel = {
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "真棒！支付成功！")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),.foregroundColor: UIColor.init(hexString: "#333333")!]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    
    fileprivate lazy var success_center_sub_label:UILabel = {
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "开始尽情地玩耍吧~")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular),.foregroundColor: UIColor.init(hex: 0x666666)!]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    fileprivate lazy var success_ok_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("好的")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.white)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 18
        control.add_touch_up(insideTarget: self, action: #selector(cancel_handle))
        return control
    }()
    
//    MARK: - Event
    @objc func cancel_handle(){
        
        
        goback_previous_controller()
        
    }
    
    @objc func confirm_handle(){
        
        ST_MaidWayManager.shared.doWay(id: self.last_selected_item.model.id, delegate: self)
        
        
    }
    
    
    func transaction_succeed(){
        
        
        root_view.isHidden = true
        
        view.addSubview(success_root_view)
        success_root_view.snp.makeConstraints { (make) in
            make.width.equalTo(320)
            make.height.equalTo(420)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        success_root_view.addSubview(success_title_btn)
        success_title_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(33)
            make.width.equalTo(170)
            make.height.equalTo(30)
        }
        
        success_root_view.addSubview(success_center_image_view)
        success_center_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(success_title_btn.snp.bottom).offset(14)
            make.width.equalTo(180)
            make.height.equalTo(120)
        }
        
        success_root_view.addSubview(success_center_label)
        success_center_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(success_center_image_view.snp.bottom).offset(27)
        }
        
        success_root_view.addSubview(success_center_sub_label)
        success_center_sub_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(success_center_label.snp.bottom).offset(5)
        }
        
        
        success_root_view.addSubview(success_ok_btn)
        success_ok_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(36)
            make.centerX.equalToSuperview()
            make.top.equalTo(success_center_sub_label.snp.bottom).offset(44)
        }
        
    }
}



extension ST_UnlockNearbyController:UITextViewDelegate{
    
    
    @available(iOS 10.0, *)
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = URL.absoluteString
        
        vc.titleStr = PH.serviceProtocolURL == vc.urlStr ? "服务条款" : "隐私政策"
        
        GlobalPresent(toController: vc)
        
        return false
    }
    
}
